<template>
	<view class="preview" v-if="currentInfo">
		<swiper circular="true" @change="onSwiperChange" :current="currentIndex" :indicator-dots="false">
			<swiper-item v-for="(item,index) in classList" :key="item._id">
				<image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<view class="mask" v-if="maskState">
			<view class="goBack" :style="{top: getStatusBarHeight()+'px'}" @click="goBack">
				<uni-icons type="left" size="28"></uni-icons>
			</view>
			<view class="count">{{currentIndex+1}}/{{classList.length}}</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer" >
				<view class="box" @click="onOpenInfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="onOpenRate">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">{{currentInfo.userScore||0}}分</view>
				</view>
				<view class="box" @click="clickDownload">
					<uni-icons type="download" size="28"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		<uni-popup ref="infoPopup" type="bottom" background-color="#fff">
			<view class="infoPopup">
				<view class="title">
					<view class=""></view>
					<text>壁纸信息</text>
					<view class="close" @click="clickInfoClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="row">
						<view class="left">壁纸ID：</view>
						<text user-select class="right">{{currentInfo.classid}}</text>
					</view>
					<view class="row">
						<view class="left">发布者：</view>
						<text class="right">{{currentInfo.nickname}}</text>
					</view>
					<view class="row">
						<view class="left">评分：</view>
						<uni-rate readonly touchable allow-half="true" class="right" :size="16"
							:value="currentInfo.score" />
						<text>{{currentInfo.score}}分</text>
					</view>
					<view class="row">
						<view class="left">摘要：</view>
						<text class="right">{{currentInfo.description}}</text>
					</view>
					<view class="row">
						<view class="left">标签：</view>
						<text class="right">
							<view class="tag" v-for="(item,index) in currentInfo.tabs" :key="index">{{item}}</view>
						</text>
					</view>
					<view class="announce">
						声明：本图片来用户投稿，非商业使用，用于免费学习
						交流，如侵犯了您的权益，您可以拷贝壁纸D举报至平
						台，邮箱513894357@qq.com,管理将删除侵权壁
						纸，维护您的权益。
					</view>
					<view class="safe-area-inset-bottom"></view>
				</scroll-view>
			</view>
		</uni-popup>
		<uni-popup ref="scorePopup" :is-mask-click="false">
			<view class="scorePopup">
				<view class="title">
					<view class=""></view>
					<text>{{isScore?'评分过了':'壁纸信息'}}</text>
					<view class="close" @click="clickRateClose">
						<uni-icons type="closeempty" size="16" color="#999"></uni-icons>
					</view>
				</view>
				<view class="rate">
					<uni-rate v-model="userScore" allowHalf :disabled="isScore" disabled-color="#FFCA3E" />
					<text class="score">{{userScore}}分</text>
				</view>
				<view class="footer">
					<button @click="submitScore" :disabled="!userScore || isScore" type="default" size="mini"
						plain="true">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad,onShareAppMessage,onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		getStatusBarHeight
	} from '@/utils/system.js'
	import {gotoHome} from '@/utils/common.js'
	import {
		apiDetailWall,
		apiGetSetUpScore,
		apiWriteDownload
	} from '@/api/apis.js'
	const maskState = ref(true);
	const infoPopup = ref(null);
	const scorePopup = ref(null);
	const rateNum = ref(0);
	const userScore = ref(0);
	const isScore = ref(false);
	const currentId = ref(null);
	const currentIndex = ref(0);
	const readImgs = ref([]);
	const currentInfo = ref(null);

	const classList = ref([]);
	const storagClassList = uni.getStorageSync('storageClassList') || []; //获取缓存


	//缺点：消耗网络资源 出现很多图一下子就加载了 swiper没有懒加载 
	classList.value = storagClassList.map(item => {
		return {
			...item,
			picurl: item.smallPicurl.replace('_small.webp', ".jpg")
		}
	})

	//遮罩层
	function maskChange() {
		maskState.value = !maskState.value;
	}
	//打开底部弹窗
	function onOpenInfo() {
		infoPopup.value.open('bottom');
	}
	//打开底部评分
	function onOpenRate() {
		console.log(currentInfo)
		if (currentInfo.value.userScore) {
			isScore.value = true;
			userScore.value = currentInfo.value.userScore;
		}
		scorePopup.value.open();
	}
	//关闭底部弹窗
	function clickInfoClose() {
		infoPopup.value.close();
		isScore.value = false;
	}
	//关闭评分
	function clickRateClose() {
		scorePopup.value.close();
		userScore.value = 0;
	}

	function goBack() {
		uni.navigateBack({
			success: () => {
				
			},
			fail: (err) => {
				uni.reLaunch({
					url:'/pages/index/index'
				})
			}
		});
	}
	//下载
	async function clickDownload() {
		// #ifdef H5
		uni.showModal({
			content: '请长按保存壁纸',
			showCancel: false
		})
		// #endif

		// #ifndef H5
		try {
			uni.showLoading({
				title: '下载中...',
				mask: true
			})
			let {
				classid,
				_id: wallId
			} = currentInfo.value;
			const res = await apiWriteDownload({
				classid,
				wallId
			});
			if (res.errCode != 0) throw res;
			uni.getImageInfo({
				src: currentInfo.value.picurl,
				success(res) {
					console.log(res);
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: res => {
							uni.showToast({
								title: "保存成功，请到相册查看",
								icon: 'none'
							})
						},
						fail: err => {
							if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: "保存失败，请重新点击下载",
									icon: 'none'
								})
								return;
							}
							uni.showModal({
								title: "授权提示",
								content: '需要授权保存相册',
								success: res => {
									if (res.confirm) {
										console.log('确认');
										uni.openSetting({
											success: (setting) => {
												console.log(setting);
												if (setting.authSetting[
														'scope.writePhotosAlbum'
														]) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'none'
													})
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: "none"
													})
												}
											}
										})
									}
								}
							})
						}
					})
				},
				complete: () => {
					uni.hideLoading();
				}
			})
		} catch (err) {
			console.log(err);
			uni.hideLoading();
		}
		// #endif
	}
	//提交评分
	async function submitScore() {
		uni.showLoading({
			title: '加载中...'
		})
		console.log(currentInfo.value);
		let {
			classid,
			_id: wallId
		} = currentInfo.value;
		let res = await apiGetSetUpScore({
			classid,
			wallId,
			userScore: userScore.value
		})
		uni.hideLoading({
			title: '加载中...'
		})
		if (res.errCode === 0) {
			uni.showToast({
				title: '评分成功',
				icon: 'none'
			})
			classList.value[currentIndex.value].userScore = userScore.value;
			currentInfo.value.userScore = userScore.value;
			//更新缓存
			uni.setStorageSync("storageClassList", classList.value);
			clickRateClose();
		}
	}
	//加载索引
	function readImgsFun() {
		readImgs.value.push(
			currentIndex.value <= 0 ? classList.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.length - 1 ? 0 : currentIndex.value + 1
		);
		readImgs.value = [...new Set(readImgs.value)];
	}

	function onSwiperChange(e) {
		isScore.value = false;
		userScore.value = 0;
		currentIndex.value = e.detail.current;
		currentInfo.value = classList.value[currentIndex.value];
		if (currentInfo.value.userScore) {
			isScore.value = true;
			userScore.value = currentInfo.value.userScore;
		}
		readImgsFun();
	}

	onLoad( async ({
		id,type
	}) => {
		if(!id)gotoHome();
		currentId.value = id;
		if(type == 'share'){
			let res = await apiDetailWall({id:currentId.value})
			classList.value = res.data.map(item=>{
				return {
					...item,
					picurl:item.smallPicurl.replace('_small.webp', ".jpg")
				}
			});
		}
		currentIndex.value = classList.value.findIndex(item => item._id === currentId.value);
		currentInfo.value = classList.value[currentIndex.value];
		readImgsFun();
	})
	
	onShareAppMessage((e)=>{
		return{
			title:'壁壁生笙，壁纸精选',
			path:`/pages/preview/preview?id=${currentId.value}&type=share`
		}
	})
	
	onShareTimeline((e)=>{
		return{
			title:'壁壁生笙，精选分类',
			query:`id=${currentId.value}&type=share`
		}
	})
	
</script>

<style lang="scss" scoped>
	.preview {
		position: relative;
		width: 100%;
		height: 100vh;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.mask {
			&>view {
				position: absolute;
				left: 0;
				margin: auto;
				color: #fff;
				right: 0;
				width: fit-content;
			}

			.goBack {
				font-size: 25rpx;
				width: 70rpx;
				height: 70rpx;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				margin-left: 0;
				border-radius: 100px;
				// top: 40rpx;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;

				:deep() {
					.uni-icons {
						color: #fff !important;
					}
				}
			}

			.count {
				top: 10vh;
				font-size: 28rpx;
				color: #fff;
				background: rgba(0, 0, 0, 0.3);
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx);
			}

			.time {
				top: calc(10vh + 80rpx);
				font-size: 140rpx;
				font-weight: 100;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.date {
				top: calc(10vh + 230rpx);
				font-size: 34rpx;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				border-radius: 120rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				align-items: center;
				align-items: center;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 12rpx;

					.text {
						font-size: 26rpx;
						color: $text-font-color-2;
					}
				}
			}
		}

		.infoPopup {
			padding: 30rpx;
		}

		.title {
			display: flex;
			font-size: 28rpx;
			justify-content: space-between;

			text {
				color: $text-font-color-2;
			}
		}

		scroll-view {
			background-color: #fff;
			width: 100%;
			max-height: 60vh;

			border-radius: 10rpx 0;

			.row {
				margin-top: 35rpx;
				display: flex;
				align-items: center;

				.left {
					width: fit-content;
					color: $text-font-color-2;
				}

				.right {
					margin-right: 10rpx;
					display: flex;
					align-items: center;

					.tag {
						display: inline-block;
						width: fit-content;
						padding: 5rpx 10rpx;
						border: 1px solid $brand-theme-color;
						color: $brand-theme-color;
						border-radius: 20rpx;
						margin-right: 20rpx;
						font-size: 28rpx;
					}
				}
			}

			.announce {
				font-size: 28rpx;
				padding: 20rpx;
				background: #F6F6F6;
				color: #666;
				border-radius: 10rpx;
				margin: 20rpx 0;
				line-height: 1.6em;
			}
		}

		.scorePopup {
			background-color: #fff;
			padding: 30rpx;
			width: 500rpx;
			border-radius: 20rpx;
			display: flex;
			flex-direction: column;

			// align-items: center;
			.rate {
				margin: 20rpx auto;
				display: flex;
				align-items: center;

				.score {
					margin-left: 20rpx;
					font-size: 30rpx;
					color: #FFCA3E;
				}
			}

			.footer {
				margin: 0 auto;
			}
		}
	}
</style>